import asyncio

from log import info, warning
from protocol_codec import encode,decode


class TcpClient:
    """异步 TCP 客户端，可主动连接 ESP32 并交互"""

    def __init__(self, host="127.0.0.1", port=8765):
        self.host = host
        self.port = port
        self.reader = None
        self.writer = None

    async def connect(self):
        self.reader, self.writer = await asyncio.open_connection(self.host, self.port)
        info(f"[Client] 已连接服务器 {self.host}:{self.port}")

    async def send(self, message):
        self.writer.write(encode(message))
        await self.writer.drain()

    async def listen(self):
        while True:
            data = await self.reader.read(1024)
            if not data:
                warning("[Client]  服务器断开连接")
                break
            msg = decode(data)
            info(f"[Client] 收到: {msg}")

    async def close(self):
        self.writer.close()
        await self.writer.wait_closed()